<?php
// +----------------------------------------------------------------------
// | UCToo [ Universal Convergence Technology ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014-2021 https://www.uctoo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Patrick <contact@uctoo.com>
// +----------------------------------------------------------------------

namespace uctoo\job;

use think\Cache;
use uctoo\ThinkEasyWeChat\Facade;
use uctoo\ThinkEasyWeChat\MiniProgram\CloudEnv\ServiceProvider;
use think\queue\Job;


class UploadCloudFunction
{

    public function fire(Job $job, $data){
        if ($job->attempts() > 30) {
            $job->delete();
            return true;
        }

        $applet = $data['applet'];
        $wechatopenInfoConfig = Cache::get('wechatopen_config');
        $openPlatform = Facade::openPlatform($wechatopenInfoConfig['app_id'],$wechatopenInfoConfig);
        $app = $openPlatform->miniProgram($applet['appid'],$applet['refresh_token']);

        /**
         * @var \uctoo\ThinkEasyWeChat\MiniProgram\CloudEnv\Client $cloud_env
         */
        $cloud_env = $app->register(new ServiceProvider)->cloud_env;
        // 校验云环境初始化状态
        $res = $cloud_env->getEnvInfo($applet['env']);
        if('NORMAL' !== $res['info_list'][0]['status']){
            $job->release(60);
            return true;
        }

        $functions = $data['cloud_functions']['functions'];
        $function_config = $data['cloud_functions']['function_config'];
        $zip = new \ZipArchive();
        foreach ($functions as $function_name){
            $cloud_env->createFunction($function_name);
            // 上传云函数zip
            $code_file = $data['cloud_functions']['code_path'].$function_name.'.zip';
            if (!file_exists($code_file)){
                continue;
            }
            $base64_file = base64_encode(file_get_contents($code_file));
            // 获取上传凭证
            $upload_params = [
                'CodeSecret' => $applet['code_secret'],
                'Handler' =>'index.main',
                'FunctionName' => $function_name,
                'EnvId' => $applet['env'],
                'InstallDependency' => 'TRUE',
                'ZipFile' => $base64_file
            ];
            $hashed_payload = hash('sha256',json_encode($upload_params,JSON_UNESCAPED_SLASHES),false);
            $signature = $cloud_env->getUploadSignature($hashed_payload);
            $headers = headers2arr($signature['headers']);
            $cloud_env->uploadCodeZip($upload_params,$headers);

            if($zip->open($code_file)){
                $function_config[$function_name][0]['config'] = json_decode($zip->getFromName('config.json'));
                $zip->close();
            }

        }

        //校验上传  此处不做细致校验，详细可校验修改时间等
        $res = $cloud_env->functionList();
        if($res['total_count'] !== count($functions)){
            $job->release(60);
            return true;
        }

        // 上传函数配置
        sleep(5);
        foreach ($function_config as $function_name => $config){
            foreach ($config as $conf){
                $cloud_env->uploadFuncConfig($function_name,json_encode($conf['config']),$conf['type']);
            }
        }



        $job->delete();

    }

    public function failed($data){

    }
}